import axios from 'axios'
import { ElMessage } from 'element-plus'
import { showFullScreenLoading, tryHideFullScreenLoading } from './loading'
import { getToken } from './cache/local-token'
import { errorHandler, handleLogout } from '@/utils/errorHandler'
import { addPendingKey, removePendingKey } from '@/utils/requestInterceptor'
import { useUserStoreHook } from '@/store'
// 开启axios请求时显示loading
axios.defaults.showLoading = true
setTimeout(() => {
  const { token } = useUserStoreHook()
  console.log(token)
})
// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 600000
})

// request interceptor
service.interceptors.request.use(
  config => {
    removePendingKey(config)
    addPendingKey(config)
    const token = getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    if (config.showLoading) {
      showFullScreenLoading()
    }
    return config
  },
  error => {
    //请求错误处理
    tryHideFullScreenLoading()
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    if (response.config.showLoading) {
      tryHideFullScreenLoading()
    }
    removePendingKey(response.config)
    const res = response.data
    // 响应数据为二进制流处理(Excel导出)
    if (response.data instanceof ArrayBuffer || response.data instanceof Blob) {
      return response
    }

    if (res.code !== 200) {
      ElMessage.error({
        message: res.message || 'Error',
        type: 'error',
        duration: 3 * 1000
      })

      // Token 过期
      if (res.code === 403) {
        handleLogout()
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    //响应错误处理
    error.config && removePendingKey(error.config)
    tryHideFullScreenLoading()
    const { response } = error
    if (response) {
      errorHandler(response.status)
      return Promise.reject(response)
    } else {
      return Promise.reject(error)
    }
  }
)

export default service
